package com.baofu.paycore.service.factory.impl;

import com.baofu.paycore.manager.model.PayBO;
import com.baofu.paycore.manager.model.RefundBO;
import com.baofu.paycore.manager.storer.OrderRepository;
import com.baofu.paycore.manager.util.RefundCheckUtil;
import com.baofu.paycore.service.facade.model.refund.req.RefundReqDTO;
import com.baofu.paycore.service.factory.OrderFactory;
import com.baofu.paycore.service.factory.PayBaseFactory;
import com.baofu.paycore.service.processor.PayBaseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 退款单构建工厂类
 * <p>
 * </p>
 * User: kwl Date: 2016/6/4 ProjectName: paycore Version: 5.0.0
 */
@Slf4j
@Service
public class RefundFactoryImpl extends PayBaseFactory implements OrderFactory<RefundReqDTO,RefundBO> {

    /**
     * 主单处理器
     * 资金单处理器 同时处理
     */
    @Resource(name = "refundProcessor")
    private PayBaseProcessor commonProcessor;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        processor.add(commonProcessor);
    }

    /**
     * 消费订单处理
     */
    @Autowired
    private OrderRepository<PayBO> payOrderRepositoryImpl;

    /**
     * 构建退款单对象
     *
     * @param refundReqDTO    退款单请求DTO对象
     * @return             退款单内部BO对象
     */
    @Override
    public RefundBO build(RefundReqDTO refundReqDTO) {

        //1、锁定支付单，避免并发退款
        PayBO payBO = payOrderRepositoryImpl.lock(refundReqDTO.getOrigRequestOrderNo(),
                refundReqDTO.getOrigRequestBizNo(),refundReqDTO.getOrigRequestSystem());

        //2、支付单可退款校验
        RefundCheckUtil.refundCheck(refundReqDTO, payBO);

        //3、退款主单信息封装
        RefundBO refundBO = new RefundBO();
        refundBO.setOldPayBO(payBO);
        refundBO.setOrigPayNo(payBO.getPayNo());
        super.buildBO(refundBO, refundReqDTO);

        return refundBO;
    }

}
